import * as XLSX from 'xlsx'
import FileSaver from "file-saver"

/**
 * 
 * @param {String} tableId 传入的DOM table ID
 * @param {String} fileName 文件名
 * @returns 
 */
export function exportClickFromTableId(tableId,fileName){
    // 设置当前日期
    let time = new Date();
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate();
    let name = year + "" + month + "" + day + fileName;
    // 通过id，获取导出的表格数据
    const wb = XLSX.utils.table_to_book(document.getElementById(tableId), {
        raw: true,
    })
    const wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
    })
    try {
        FileSaver.saveAs(
        new Blob([wbout], {
        type: "application/octet-stream",
        }),
        name + ".xlsx"
    )} catch (e) {
        console.log(e)
    }
    return wbout
}

// 字符串转二进制
/**
 * 使用数组对象导出时，需要进行字符串转二进制，通过tableID（DOM元素）导出则不需要
 * @param {*} s Excel的配置
 * @returns 
 */
function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}

/**
 * 
 * @param {Array} tableData 表格数组对象
 * @param {String} fileName 文件名
 * @returns 
 */
export function exportClickFromDatas(tableData,fileName){
    // 设置当前日期
    let time = new Date();
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate();
    let name = year + "" + month + "" + day + fileName;
    // 通过传入的数组对象，获取导出的表格数据
    const workbook = XLSX.utils.book_new(); // 创建工作簿    
    const worksheet = XLSX.utils.json_to_sheet(tableData); // 将数据转换为工作表    
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); // 将工作表添加到工作簿    
    const wbout = XLSX.write(workbook, { 
        bookType: 'xlsx', 
        type: 'binary'
    }); // 生成Excel的配置    
    const blob = new Blob([s2ab(wbout)], { 
        type: 'application/octet-stream' 
    }); // 创建二进制对象并创建url

    // 使用FileSaver库保存文件
    try {
        FileSaver.saveAs(
            blob, 
            name + ".xlsx"
        )
    } catch (e) {
        console.log(e)
    }
    return wbout
}
